import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QHBoxLayout, QPushButton, QLabel, QSpinBox, 
                             QFileDialog, QMessageBox, QFrame)
from PyQt6.QtGui import QPixmap, QFont
from PyQt6.QtCore import Qt
from PIL import Image
import os


class ImageEditor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.image = None
        self.original_image = None
        self.current_pixmap = None
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('图片编辑器')
        self.setGeometry(100, 100, 800, 600)
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f0f0;
            }
            QPushButton {
                background-color: #4CAF50;
                border: none;
                color: white;
                padding: 10px 20px;
                text-align: center;
                font-size: 14px;
                margin: 4px 2px;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QLabel {
                font-size: 12px;
                color: #333;
            }
            QSpinBox {
                padding: 5px;
                font-size: 12px;
                border: 2px solid #ddd;
                border-radius: 3px;
            }
        """)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        main_layout = QVBoxLayout(central_widget)

        # 按钮区域
        button_layout = QHBoxLayout()
        
        self.upload_btn = QPushButton('上传图片')
        self.upload_btn.clicked.connect(self.upload_image)
        
        self.save_btn = QPushButton('保存图片')
        self.save_btn.clicked.connect(self.save_image)
        self.save_btn.setEnabled(False)
        
        button_layout.addWidget(self.upload_btn)
        button_layout.addWidget(self.save_btn)
        button_layout.addStretch()

        # 尺寸调整区域
        size_frame = QFrame()
        size_frame.setFrameStyle(QFrame.Shape.Box)
        size_layout = QHBoxLayout(size_frame)
        
        width_label = QLabel('宽度:')
        self.width_spinbox = QSpinBox()
        self.width_spinbox.setRange(1, 5000)
        self.width_spinbox.setSuffix(' px')
        self.width_spinbox.setEnabled(False)  # 初始禁用，上传图片后启用
        self.width_spinbox.valueChanged.connect(self.update_image_size)
        
        height_label = QLabel('高度:')
        self.height_spinbox = QSpinBox()
        self.height_spinbox.setRange(1, 5000)
        self.height_spinbox.setSuffix(' px')
        self.height_spinbox.setEnabled(False)  # 初始禁用，上传图片后启用
        self.height_spinbox.valueChanged.connect(self.update_image_size)
        
        self.reset_btn = QPushButton('重置尺寸')
        self.reset_btn.clicked.connect(self.reset_size)
        self.reset_btn.setEnabled(False)
        
        size_layout.addWidget(width_label)
        size_layout.addWidget(self.width_spinbox)
        size_layout.addWidget(height_label)
        size_layout.addWidget(self.height_spinbox)
        size_layout.addWidget(self.reset_btn)
        size_layout.addStretch()

        # 图片显示区域
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.image_label.setStyleSheet("""
            QLabel {
                border: 2px dashed #aaa;
                background-color: white;
                min-height: 400px;
                color: #666;
                font-size: 16px;
            }
        """)
        self.image_label.setText('点击"上传图片"开始编辑')

        # 信息显示区域
        self.info_label = QLabel('等待上传图片...')
        self.info_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.info_label.setStyleSheet("color: #666; font-size: 12px; padding: 10px;")

        main_layout.addLayout(button_layout)
        main_layout.addWidget(size_frame)
        main_layout.addWidget(self.image_label, 1)
        main_layout.addWidget(self.info_label)

    def upload_image(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, '选择图片', '', 
            'Image Files (*.png *.jpg *.jpeg *.bmp *.gif *.tiff)'
        )
        
        if file_path:
            try:
                self.original_image = Image.open(file_path)
                self.image = self.original_image.copy()
                
                # 启用SpinBox并设置值（临时断开信号避免触发resize）
                self.width_spinbox.setEnabled(True)
                self.height_spinbox.setEnabled(True)
                self.width_spinbox.blockSignals(True)
                self.height_spinbox.blockSignals(True)
                self.width_spinbox.setValue(self.image.width)
                self.height_spinbox.setValue(self.image.height)
                self.width_spinbox.blockSignals(False)
                self.height_spinbox.blockSignals(False)
                
                # 显示图片
                self.display_image()
                
                # 启用按钮
                self.save_btn.setEnabled(True)
                self.reset_btn.setEnabled(True)
                
                # 更新信息
                self.update_info()
                
            except Exception as e:
                QMessageBox.critical(self, '错误', f'无法加载图片: {str(e)}')

    def display_image(self):
        if self.image:
            # 将PIL图片转换为QPixmap
            img_rgb = self.image.convert('RGB')
            img_rgb.save('temp_image.jpg', 'JPEG')
            
            pixmap = QPixmap('temp_image.jpg')
            
            # 缩放图片以适应显示区域
            scaled_pixmap = pixmap.scaled(
                self.image_label.size() * 0.9,
                Qt.AspectRatioMode.KeepAspectRatio,
                Qt.TransformationMode.SmoothTransformation
            )
            
            self.image_label.setPixmap(scaled_pixmap)
            self.current_pixmap = pixmap
            
            # 删除临时文件
            try:
                os.remove('temp_image.jpg')
            except:
                pass

    def update_image_size(self):
        if self.image:
            new_width = self.width_spinbox.value()
            new_height = self.height_spinbox.value()
            
            try:
                self.image = self.original_image.resize((new_width, new_height), Image.Resampling.LANCZOS)
                self.display_image()
                self.update_info()
            except Exception as e:
                QMessageBox.warning(self, '警告', f'调整尺寸时出错: {str(e)}')

    def reset_size(self):
        if self.original_image:
            self.image = self.original_image.copy()
            self.width_spinbox.setValue(self.original_image.width)
            self.height_spinbox.setValue(self.original_image.height)
            self.display_image()
            self.update_info()

    def update_info(self):
        if self.image:
            original_size = f"{self.original_image.width}x{self.original_image.height}"
            current_size = f"{self.image.width}x{self.image.height}"
            self.info_label.setText(f'原始尺寸: {original_size} | 当前尺寸: {current_size}')

    def save_image(self):
        if self.image:
            file_path, _ = QFileDialog.getSaveFileName(
                self, '保存图片', '', 
                'PNG (*.png);;JPEG (*.jpg);;BMP (*.bmp);;TIFF (*.tiff)'
            )
            
            if file_path:
                try:
                    self.image.save(file_path)
                    QMessageBox.information(self, '成功', '图片保存成功！')
                except Exception as e:
                    QMessageBox.critical(self, '错误', f'保存图片失败: {str(e)}')


def main():
    app = QApplication(sys.argv)
    
    # 设置应用程序字体
    font = QFont('Microsoft YaHei', 10)
    app.setFont(font)
    
    editor = ImageEditor()
    editor.show()
    
    sys.exit(app.exec())


if __name__ == '__main__':
    main()